/****************************************************************************
 * Copyright (C) 2012 Dj_Skual
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/
#include "FileLoadTask.h"
#include "../Controls/Application.h"
#include "fileops.h"

FileLoadTask::FileLoadTask(const std::string &filepath, bool silent, bool autoDelete)
	: destPath(filepath)
	, m_silent(silent)
	, bAutoDelete(autoDelete)
{
	ThreadedTaskHandler::Instance()->AddTask(this);
}

void FileLoadTask::Execute(void)
{
	if(destPath.empty())
	{
		if(bAutoDelete)
			Application::Instance()->PushForDelete(this);
		return;
	}
	
	u8 *buffer = NULL;
	u32 buffer_size = 0;

	int result;

	if(m_silent)
		result = LoadFileToMem(destPath, &buffer, &buffer_size);
	else
		result = LoadFileToMemWithProgress("Loading file:", destPath, &buffer, &buffer_size);

	if(!buffer || result < 0)
	{
		if(buffer)
			free(buffer);
		LoadingFailed(result);
	}
	else
		LoadingComplete(buffer, buffer_size);
	
	if(bAutoDelete)
		Application::Instance()->PushForDelete(this);
}
